package cn.edu.lzzy.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Pattern;

public class StringUtils {
    //手机校验正则表达式
    private static final String REGEX_MOBILE="((\\+86|0086)?\\s*)((134[0-8]\\d{7})|" +
            "(((13([0-3]|[5-9]))|(14[5-9])|15([0-3]|[5-9])|(16(2|[5-7]))|17([0-3]|[5-8])|" +
            "18[0-9]|19(1|[8-9]))\\d{8})|(14(0|1|4)0\\d{7})|(1740([0-5]|[6-9]|[10-12])\\d{7}))";
    //Email校验正则表达式
    private static final String REGEX_MAIL="^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";

    //空串判断
    public static boolean isEmpty(String str){
        return str == null|| str.isEmpty();
    }
    //验证手机号码合法性
    public static boolean validPhone(String phone){
        if(StringUtils.isEmpty(phone)){
            return false;
        }
        return Pattern.matches(REGEX_MOBILE,phone);
    }
    //验证邮箱合法性
    public static boolean validMail(String mail){
        if(StringUtils.isEmpty(mail)){
            return false;
        }
        return Pattern.matches(REGEX_MAIL,mail);
    }

    /**
     * 实现类算法处理，和加盐
     *  origin ：初始子串
     *  salt：加盐子串
     * @return
     */
    public static String md5Encode(String origin,String salt){
    try{
        /**
         * MessageDigest类：提供信息摘要算法功能，例如：MD5,SHA算法
         * 信息照耀是单向Hash函数，它可以接收任意大小的数据，输出稳定长度的hash值
         */
        MessageDigest digest = MessageDigest.getInstance("MD5");
        if(!isEmpty(salt)){
            origin+=salt;
        }
        digest.update(origin.getBytes());
        //生产16进制的字符串
        byte[] bytes = digest.digest();
        int i;
        StringBuilder builder = new StringBuilder();
        for (byte b: bytes) {
            i=b;
            if(i<0){
                i+=256;
            }
            if(i<16){
                builder.append("0");
            }
            builder.append(Integer.toHexString(i));//toHexString():返回16进制的字符串

        }

            return builder.toString();
    }catch (NoSuchAlgorithmException ex){
        ex.printStackTrace();
        return null;
    }

    }

    public static String padLeft(String src,int len,char patch){
        int diff=len-src.length();
        if(diff<=0){
            return src;
        }
        char[] chars=new char[len];
        System.arraycopy(src.toCharArray(),0,chars,diff,src.length());
        for (int i = 0; i < diff; i++) {
            chars[i]=patch;
        }
        return new String(chars);
    }
    public static String padRight(String src,int len,char patch){
        int diff=len-src.length();
        if(diff<=0){
            return src;
        }
        char[] chars=new char[len];
        System.arraycopy(src.toCharArray(),0,chars,0,src.length());
        for (int i = src.length(); i < len; i++) {
            chars[i]=patch;
        }
        return new String(chars);
    }
}
